package sysAuth

import grails.converters.JSON
import initConfig.SysInitData
import sysUtil.ResultCode
import sysUtil.ResultJson
import sysUtil.SysCommUtil
import xdInterface.XdControllerInterface

class UserController implements XdControllerInterface {

    def authUtilsService

    def index() {query()}

    @Override
    def delete() {
        del()
    }
    @Override
    def detail() {
        return null
    }

    @Override
    def del() {
        def result = ResultJson.resultMap()
        try {
            def adminUser = SysUsers.findByUserNo(params.userNo)
            def userGrade = authUtilsService.isAvailable(adminUser)
            if(SysInitData.USER_GRADE_ADMIN_DATA.contains(userGrade)){
                def delUser = SysUsers.get(Long.parseLong(params?.id))
                SysUserRoles.findAllByUser(delUser).each {
                    it.delete(flush: true)
                }
                delUser.delete(flush: true)
                result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            }else {
                result.put(ResultJson.CODE.name,ResultCode.OPT_NOT_AUTH.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_NOT_AUTH.message)
            }
        }catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
        }finally{
            render  result as JSON
        }
    }

    @Override
    def edit() {
        save()
    }

    @Override
    def save() {
        def result = ResultJson.resultMap()

        try {
            def userCode = params.userCode
            def user = SysUsers.findByUserNo(userCode)
            if(user){//如果用户存在则，返回exists异常
                //user.userNo = userCode
                user.userName = params.userName
                //user.passWord =  String.valueOf(params?.passWord).encodeAsMD5()
                user.deptId = Integer.parseInt(params?.deptId)
                user.orgId = Integer.parseInt(params?.orgId)
                user.email = params?.email
                user.phone = params?.phone
                user.qq = params?.qq
                user.weiXin = params?.weiXin
                user.gender = params?.gender
                user.updater = params.updater
                user.birth = params?.birth
                user.isActive = params.isActive?:user.isActive
                user.salary = params.salary ?Float.parseFloat(params.salary):user.salary
                user.education = params?.education
                user.position = params?.position
                user.address = params?.address
                user.save(flush: true)

                result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            }else {
                result.put(ResultJson.CODE.name,ResultCode.NOT_EXISTS_ERROR.code)
                result.put(ResultJson.MSG.name,ResultCode.NOT_EXISTS_ERROR.message)
            }
        }catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            render  result as JSON
        }
    }

    @Override
    def update() {
        return null
    }

    @Override
    def add() {
        def result = ResultJson.resultMap()

        try {
            def userCode = String.valueOf(params.userCode).toLowerCase()
            def user = SysUsers.findByUserNo(userCode)
            if(user){//如果用户存在则，返回exists异常
                result.put(ResultJson.CODE.name,ResultCode.EXISTS_ERROR.code)
                result.put(ResultJson.MSG.name,ResultCode.EXISTS_ERROR.message)
            }else{

                user = new SysUsers(
                        userNo: userCode,userName: params.userName,
                        passWord: String.valueOf(123456).encodeAsMD5(),
                        deptId: params?.deptId,orgId:  params?.orgId ,
                        email: params?.email,phone: params?.phone,qq: params?.qq,weiXin: params?.weiXin,
                        gender: params?.gender,creator:params.userNo,birth: params?.birth )

                user.isActive = params?.isActive
                user.salary = Float.parseFloat(params.salary?:"0")
                user.education = params?.education
                user.position = params?.position
                user.address = params?.address


                user.save(flush: true)
                result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
                result.put(ResultJson.MSG.name,ResultCode.OPT_SUCCESS.message)
            }
        }catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
        }finally{
            render  result as JSON
        }
    }

    @Override
    def dowLoad() {
        return null
    }

    @Override
    def upLoad() {
        return null
    }

    @Override
    def query() {
        def result = ResultJson.resultMap()
        try {
            def resultMap = authUtilsService.getUserListByAuth(params)
            //def buttonAuth = authUtilsService.getFuncOptsByAuth(params)
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.DATA.name,resultMap.list )
            result.put(ResultJson.COUNT.name,resultMap.count)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            //println result.toString()
            render result as JSON
        }
    }

    @Override
    def getOne() {

        def result = ResultJson.resultMap()
        try {
            def id =params?.id
            def userCode = params?.userCode
            def user
            if(!id){
                user = SysUsers.findByUserNo(userCode)
            }else{
                user = SysUsers.get( Integer.parseInt(params?.id))
            }

            result.put(ResultJson.DATA.name,SysCommUtil.domainToMap(user))
            result.put(ResultJson.CODE.name,ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name,ResultCode.TABLE_DATA_SUCCESS.message)
        }catch (Exception e){
            result.put(ResultJson.CODE.name,ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name,ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        }finally{
            //println result.toString()
            render result as JSON
        }
    }


    /**
     * 获取部门下拉框树
     */
    def selectDeptTreeData(){
        def result = ResultJson.resultJson()
        result.put(ResultJson.DATA.name , authUtilsService.selectDeptTreeData(params))
        render result
    }

    /**
     * 获取区域下拉框树
     * @return
     */
    def selectOrgTreeData(){
        def result = ResultJson.resultJson()
        result.put(ResultJson.DATA.name , authUtilsService.selectOrgTreeData(params))

        render result
    }


    /**
     * 修改用户密码:返回用户信息
     * @return
     */
    def resetPassword() {
        def result = ResultJson.resultJson()
        try {
            SysUsers user = SysUsers.get(Long.parseLong(params.id))
            def passWord = String.valueOf(Math.round(Math.random()*1000000))
            user.setPassWord(passWord.encodeAsMD5())
            user.save(flush: true)
            result.put(ResultJson.DATA.name,passWord)
            result.put(ResultJson.CODE.name, ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name, ResultCode.OPT_SUCCESS.message)
        } catch (Exception e) {
            result.put(ResultJson.CODE.name, ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name, ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        } finally {
            render result.toString()
        }
    }

    /**
     * 修改用户密码:返回修改结果
     * @return
     */
    def changePassword() {
        def result = ResultJson.resultJson()
        def userNo = params?.userCode
        //def userName = params?.userName
        def oldPassWord = String.valueOf(params?."oldPassWord")
        def passWord = String.valueOf(params?."passWord")
        def rePassWord = String.valueOf(params?."repassWord")
        try {
            SysUsers user = SysUsers.findByUserNo(userNo)
            if (!user) {
                result.put(ResultJson.CODE.name, ResultCode.USER_NOT_EXIST.code)
                result.put(ResultJson.MSG.name, ResultCode.USER_NOT_EXIST.message)
            }else if(passWord.trim()  != rePassWord.trim() ){
                result.put(ResultJson.CODE.name, ResultCode.OLD_PWD_ERROR.code)
                result.put(ResultJson.MSG.name,"2次新密码输入不一致" )
            } else {
                if(user.passWord !=  oldPassWord.trim().encodeAsMD5()){
                    result.put(ResultJson.CODE.name, ResultCode.OLD_PWD_ERROR.code)
                    result.put(ResultJson.MSG.name, ResultCode.OLD_PWD_ERROR.message)
                }else{
                    user.setPassWord(passWord.encodeAsMD5())
                    user.setUpdater(params?.updater)
                    user.save(flush: true)
                    result.put(ResultJson.MSG.name,"密码修改成功")
                }
            }
        } catch (Exception e) {
            result.put(ResultJson.CODE.name, ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name, ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        } finally {
            //println result;
            render result.toString()
        }
    }

    /**
     * 用户列表 下拉框
     * @return
     */
    def getUserSelectList(){
        def result = ResultJson.resultJson()
        try {
            def list = authUtilsService.getUserSelectList(params)
            result.put(ResultJson.DATA.name,list)
            result.put(ResultJson.CODE.name, ResultCode.TABLE_DATA_SUCCESS.code)
            result.put(ResultJson.MSG.name, ResultCode.OPT_SUCCESS.message)
        } catch (Exception e) {
            result.put(ResultJson.CODE.name, ResultCode.QUERY_ERROR.code)
            result.put(ResultJson.MSG.name, ResultCode.QUERY_ERROR.message)
            e.printStackTrace()
        } finally {
            //println result;
            render result.toString()
        }
    }
}
